<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org 
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\admin\middleware;

use app\admin\model\SystemAdmin;
use app\admin\model\SystemAuthNode;
use app\admin\model\SystemNode;
use app\admin\service\SystemLogService;
use app\Request;
use EasyAdmin\tool\CommonTool;
use think\Exception;
use think\facade\Log;

/**
 * 系统操作日志中间件
 * Class SystemLog
 *
 * @package app\admin\middleware
 */
class SystemLog
{

    /**
     * 敏感信息字段，日志记录时需要加密
     *
     * @var array
     */
    protected $sensitiveParams = [
        'password',
        'password_again',
        'phone',
        'mobile'
    ];
    /**
     * 保留操作
     *
     * @var array
     */
    protected $sensitiveMethod = [
        'login' => '管理员登陆',
        'ueditor' => 'ueditor编辑器',
        'ajax' => '后台文件上传',
    ];

    public function handle(Request $request, \Closure $next)
    {
        $params = $request->param();
        $adminid = session('admin.id');
        if(!$adminid && isset($params['username'])){
            $adminid = SystemAdmin::where('username', $params['username'])
                ->value('id');
        }
        if (isset($params['s'])) {
            unset($params['s']);
        }
        foreach ($params as $key => $val) {
//            in_array($key, $this->sensitiveParams) && $params[$key] = "***********";
            in_array($key, $this->sensitiveParams) && $params[$key] = encrypt($params[$key]);
        }
        $method = strtolower($request->method());
        $url = $request->url();
        $title = '';
        foreach ($this->sensitiveMethod as $k => $v) {
            if (strpos(strtolower($url), $k) !== false && $method == 'post') {
                $title = $v;
                break;
            }
        }
        if (empty($title)) {
            $title = SystemNode::where('node', str_replace('/admin/','',parse_url($url)['path']))->value('title') ?? '';
        }

        trace(['url' => $url, 'method' => $method, 'params' => $params,], 'requestDebugInfo');

        if ($request->isAjax()) {
            if (in_array($method, ['post', 'put', 'delete'])) {
                $ip = CommonTool::getRealIp();
                $data = [
                    'admin_id' => $adminid,
                    'title' => $title,
                    'url' => $url,
                    'method' => $method,
                    'ip' => $ip,
                    'content' => json_encode($params, JSON_UNESCAPED_UNICODE),
                    'useragent' => $_SERVER['HTTP_USER_AGENT'],
                    'create_time' => time(),
                ];
                SystemLogService::instance()->save($data);
            }
        }
        return $next($request);
    }

}